<template>
  <van-popup
    v-model="show"
    position="bottom"
    round
    safe-area-inset-bottom
    @closed="onCancel"
  >
    <div class="time-picker">
      <van-picker
        :columns="columns"
        :default-index="defaultIndexes"
        show-toolbar
        title="选择配送时间"
        @confirm="onConfirm"
        @change="onChange"
        @cancel="onCancel"
      />
    </div>
  </van-popup>
</template>

<script>
export default {
  name: "TimePicker",
  model: {
    prop: 'visible',
    event: 'visible-change'
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    maxDays: {
      type: Number,
      default: 2
    },
    dispatchStart: {
      type: String,
      default: "07:30"
    },
    dispatchEnd: {
      type: String,
      default: "22:30"
    }
  },

  data() {
    return {
      currentDate: new Date(), //默认当前时间
      weekDays: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
      columns: [],
      selectedValues: {
        date: "",
        timeSlot: ""
      },
      defaultIndexes: [0, 0]
    };
  },

  computed: {
    show: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('visible-change', val);
      }
    },
    // 生成日期选项
    dateOptions() {
      const dates = [];

      for (let i = 0; i < this.maxDays; i++) {
        const date = new Date(this.currentDate);
        date.setDate(this.currentDate.getDate() + i);

        const month = (date.getMonth() + 1).toString().padStart(2, "0");
        const day = date
          .getDate()
          .toString()
          .padStart(2, "0");
        const value = `${date.getFullYear()}-${month}-${day}`;

        dates.push({
          text: i === 0 ? `今天 (${this.weekDays[date.getDay()]})` : `${month}-${day} ${this.weekDays[date.getDay()]}`,
          value: value,
          isToday: i === 0
        });
      }

      return dates;
    },

    // 生成时间段选项，包括末尾不足一小时的时间段
    timeSlotOptions() {
      const slots = [];
      const [startHour, startMinute] = this.dispatchStart.split(":").map(Number);
      const [endHour, endMinute] = this.dispatchEnd.split(":").map(Number);

      // 转换为分钟计算
      let currentMinutes = startHour * 60 + startMinute;
      const endMinutes = endHour * 60 + endMinute;

      while (currentMinutes < endMinutes) {
        let nextSlotMinutes = currentMinutes + 60;

        // 确保不超过结束时间
        if (nextSlotMinutes > endMinutes) {
          nextSlotMinutes = endMinutes;
        }

        const startTime = this.minutesToTimeString(currentMinutes);
        const endTime = this.minutesToTimeString(nextSlotMinutes);

        const timeSlot = {
          text: `${startTime}-${endTime}`,
          value: `${startTime}-${endTime}`,
          startMinutes: currentMinutes,
          endMinutes: nextSlotMinutes,
          disabled: this.isSelectedDateToday && currentMinutes <= this.currentDate.getHours() * 60 + this.currentDate.getMinutes()
        };

        slots.push(timeSlot);
        currentMinutes = nextSlotMinutes;

        // 如果已经到达结束时间，停止循环
        if (currentMinutes >= endMinutes) {
          break;
        }
      }

      return slots;
    },

    // 判断选择的日期是否是今天
    isSelectedDateToday() {
      if (!this.selectedValues.date) return false;
      const selectedDate = new Date(this.selectedValues.date);
      return selectedDate.getDate() === this.currentDate.getDate() && selectedDate.getMonth() === this.currentDate.getMonth() && selectedDate.getFullYear() === this.currentDate.getFullYear();
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.initialize();
      }
    }
  },
  methods: {
    // 将分钟数转换为时间字符串 (HH:MM)
    minutesToTimeString(minutes) {
      const hour = Math.floor(minutes / 60);
      const minute = minutes % 60;
      return `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}`;
    },

    // 更新选择器配置
    updateColumns() {
      this.columns = [
        {
          values: this.dateOptions,
          defaultIndex: 0,
          className: "column-date"
        },
        {
          values: this.timeSlotOptions,
          defaultIndex: this.getDefaultTimeIndex(),
          className: "column-time"
        }
      ];
    },

    // 获取默认时间索引
    getDefaultTimeIndex() {
      if (this.isSelectedDateToday) {
        const index = this.timeSlotOptions.findIndex(option => !option.disabled);
        return index >= 0 ? index : 0;
      }
      return 0;
    },

    // 选择变化处理
    onChange(picker, values, index) {
      const dateValue = values[0]?.value;
      const timeSlotValue = values[1]?.value;

      // 更新选中值
      this.selectedValues = {
        date: dateValue,
        timeSlot: timeSlotValue
      };

      // 如果切换了日期，需要更新时间列表
      if (index === 0) {
        // 更新时间列选项
        const newTimeOptions = this.timeSlotOptions;
        picker.setColumnValues(1, newTimeOptions);

        // 如果是今天，自动滚动到第一个可用时间段
        if (this.isSelectedDateToday) {
          const firstAvailableIndex = newTimeOptions.findIndex(option => !option.disabled);
          if (firstAvailableIndex >= 0) {
            picker.setColumnIndex(1, firstAvailableIndex);
          }
        }
      }
    },

    // 确认选择
    onConfirm(values) {
      const dateValue = values[0]?.value;
      const timeSlotValue = values[1]?.value;

      // 检查选中的时间段是否有效
      const selectedTimeSlot = this.timeSlotOptions.find(slot => slot.value === timeSlotValue);

      if (this.isSelectedDateToday && selectedTimeSlot?.disabled) {
        this.$toast("请选择有效的配送时间段");
        return;
      }

      const [startTime, endTime] = timeSlotValue.split("-");

      this.$emit("change", {
        date: dateValue,
        timeSlot: timeSlotValue,
        startTime: new Date(`${dateValue} ${startTime}`).getTime(),
        endTime: new Date(`${dateValue} ${endTime}`).getTime(),
      });
    },

    // 取消选择
    onCancel() {
      this.$emit("cancel");
    },

    // 初始化
    initialize() {
      // 设置初始选中值为今天
      this.selectedValues.date = this.dateOptions[0].value;

      // 找到今天第一个可用的时间段
      const firstAvailableSlot = this.timeSlotOptions.find(option => !option.disabled);
      if (firstAvailableSlot) {
        this.selectedValues.timeSlot = firstAvailableSlot.value;
        this.defaultIndexes[1] = this.timeSlotOptions.findIndex(option => option.value === firstAvailableSlot.value);
      }

      this.updateColumns();
    }
  },

  created() {
    this.initialize();
  }
};
</script>

<style lang="scss" scoped>
.time-picker {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(100, 101, 102, 0.12);

  ::v-deep .van-picker {
    &__toolbar {
      border-bottom: 1px solid #ebedf0;
    }

    &-column {
      &--0 {
        flex: 0.8;
      }

      &--1 {
        flex: 1.2;
      }

      &__item {
        padding: 0 16px;

        &--disabled {
          opacity: 0.3;
          color: #999;
        }
      }
    }
  }

  .column-date {
    font-size: 14px;
  }

  .column-time {
    font-size: 14px;
  }
}
</style>
